//
//  ConnectViewController.m
//  Riese
//
//  Created by air on 2019/10/23.
//  Copyright © 2019 wangjinyu. All rights reserved.
//

#import "ConnectViewController.h"
#import "ConnectCell.h"
#import "DeviceCommand.h"
#import <MMAlertView.h>

@interface ConnectViewController () <UITableViewDelegate, UITableViewDataSource, CBCentralManagerDelegate, DeviceCommandDelegate> {
    DeviceCommand *device;

    CBCentralManager *manager;
    CBPeripheral *peripheralFind;
    
    Boolean bReSend;
    NSTimer *timer;
}

@property (nonatomic, strong) UITableView *mainTable;
@property (nonatomic, strong) NSArray *deviceArr;

@property (nonatomic, strong) FMDatabase *db;
@property (nonatomic, strong) NSArray *dataArr;

@end

@implementation ConnectViewController

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = kColor(243, 243, 243);
    self.navigationItem.title = NSLocalizedString(@"Device", nil);
    
    #if TARGET_IPHONE_SIMULATOR
        
    #else
        device = [[DeviceCommand alloc] init];
    #endif
    
    [self makeNav];
    [self connectDevice];
    [self makeUI];
}

- (void)makeNav {
    UIButton *refreshBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    refreshBtn.frame = CGRectMake(0, 0, kNavHeight, kNavHeight);
    [refreshBtn setImage:[UIImage imageNamed:@"refresh"] forState:UIControlStateNormal];
    [refreshBtn addTarget:self action:@selector(refreshBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:refreshBtn];
}

- (void)makeUI {
    self.mainTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - kBottomSafeHeight)];
    self.mainTable.backgroundColor = [UIColor whiteColor];
    self.mainTable.delegate = self;
    self.mainTable.dataSource = self;
    self.mainTable.showsVerticalScrollIndicator = NO;
    self.mainTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.mainTable.estimatedRowHeight = 0;
    self.mainTable.estimatedSectionHeaderHeight = 0;
    self.mainTable.estimatedSectionFooterHeight = 0;
    [self.view addSubview:self.mainTable];
}

#pragma mark - tableView delegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellIdentifier = @"ConnectCell";
    ConnectCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[NSBundle mainBundle] loadNibNamed:cellIdentifier owner:self options:nil].firstObject;
    }
    
    if (self.deviceArr.count > 0) {
        cell.titleStr = self.deviceArr[indexPath.row];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.deviceArr.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    if ((manager != nil) && (peripheralFind != nil)) {
//        [manager connectPeripheral:peripheralFind options:nil];
//    }
//
    if ((manager != nil) && (peripheralFind != nil)) {
        [SVProgressHUD showWithStatus:NSLocalizedString(@"Connection", nil)];
        [manager connectPeripheral:peripheralFind options:nil];
    }
}

#pragma mark - 连接设备
- (void)connectDevice {
//    #if TARGET_IPHONE_SIMULATOR
//
//    #else
//        device = [[DeviceCommand alloc] init];
//    #endif
//    device = [[DeviceCommand alloc] init];
    device.delegate = self;

    bReSend = YES;
    
    NSLog(@"findDevice");
    
    if (manager != nil)
    {
        if (peripheralFind != nil)
        {
            [manager cancelPeripheralConnection:peripheralFind];
        }
        
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:false], CBCentralManagerScanOptionAllowDuplicatesKey, nil];
        
        [manager scanForPeripheralsWithServices:nil options:dic];
    }
    else
    {
        CBCentralManager *managerFind = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
        
        manager = managerFind;
    }
    
    // 30秒之后没有搜到设备提示 050428
    [SVProgressHUD showWithStatus:NSLocalizedString(@"searching", nil)];
    timer = [NSTimer timerWithTimeInterval:30.0 target:self selector:@selector(timerRun) userInfo:nil repeats:NO];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}

- (void)timerRun {
    [SVProgressHUD dismiss];
    [YJProgressHUD showMessage:NSLocalizedString(@"Device not found", nil) inView:self.view];
}

#pragma mark ----<DeviceCommandDelegate>
-(void)getDeviceData:(NSDictionary *)dicDeviceData {
    // 获取完数据
    // 将新数据插入到数据库 连接设备后, 将数据存储到 DeviceData 表中, 外键与 userInfo 表主键相关联
    // 创建数据库对象
    [SVProgressHUD dismiss];
    if ([dicDeviceData[@"DataCount"] integerValue] > 0) {
        self.dataArr = dicDeviceData[@"DeviceData"];
        NSString * docsdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString * path = [docsdir stringByAppendingPathComponent:@"DeviceData.sqlite"];//将需要创建的串拼接到后面
        self.db = [FMDatabase databaseWithPath:path];

        // 建表
        [self createTable];
    }
    else {
        NSString *detail = [NSString stringWithFormat:@"%@%@", peripheralFind.name, NSLocalizedString(@"nonewdata", nil)];
        MMAlertView *alert = [[MMAlertView alloc] initWithTitle:NSLocalizedString(@"tip", nil) detail:detail items:@[MMItemMake(NSLocalizedString(@"sure", nil), MMItemTypeNormal, ^(NSInteger index) {
            
        })]];
        [alert show];
    }
}

-(void)getOperateResult:(NSDictionary *)dicDeleteResult
{
    NSLog(@"getOperateResult %@", dicDeleteResult);
}

-(void)getError:(NSDictionary *)dicError
{
    [SVProgressHUD dismiss];
    NSLog(@"getError %@", dicError);
//    [YJProgressHUD showMessage:[NSString stringWithFormat:@"ERROR %@",dicError] inView:self.view];
}

-(void)receivePM10Param:(NSDictionary *)dicParam//15.1.20
{
    // 获取参数
    NSLog(@"getPM10Param %@", dicParam);
}

- (void)receivePM10DataProgress:(NSInteger)progress {
    NSLog(@"PM10 progress = %ld",(long)progress);
//    [YJProgressHUD showMessage:[NSString stringWithFormat:@"%ld",(long)progress] inView:self.view];
}

- (void)synchronizeTimeFlag:(BOOL)success {
    
    NSLog(@"同步时间 %@", success?@"成功":@"失败");
    
    [device synchronizeTime:peripheralFind];
}

- (void)receivePM10DataList:(NSArray *)dataList {
    
//    [self.view makeToast:@"获取到数据列表了"];
    NSLog(@"dataList %@",dataList);
}

- (void)receiveRealTimeOxygenPulse:(NSDictionary *)dic {
    
//    NSLog(@"pulse %d, oxygen %d, PI %.2f",[[dic objectForKey:@"pulse"] integerValue],[[dic objectForKey:@"oxygen"] integerValue],[[dic objectForKey:@"PI"] floatValue]);
}

- (void)receiveRealTimePulseWaveData:(NSDictionary *)dic {
    
    NSLog(@"signal intensity %d, pulseWave %d, barGraph %d",[[dic objectForKey:@"signalIntensity"] integerValue], [[dic objectForKey:@"pulseWave"] integerValue], [[dic objectForKey:@"barGraph"] integerValue]);
}

#pragma mark ----  <CBCentralManagerDelegate>
-(void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSMutableString *nsmstring = [NSMutableString stringWithString:@"UpdateState:"];
    switch (central.state)
    {
        case CBManagerStateUnknown:
        {
            [nsmstring appendString:@"Unknown\n"];
            break;
        }
        case CBManagerStateUnsupported:
        {
            [nsmstring appendString:@"Unsupported\n"];
            break;
        }
        case CBManagerStateUnauthorized:
        {
            [nsmstring appendString:@"Unauthorized\n"];
            break;
        }
        case CBManagerStateResetting:
        {
            [nsmstring appendString:@"Resetting\n"];
            break;
        }
        case CBManagerStatePoweredOff:
        {
            [nsmstring appendString:@"PoweredOff\n"];
            if(peripheralFind != NULL)
            {
                [manager cancelPeripheralConnection:peripheralFind];
            }
            break;
        }
        case CBManagerStatePoweredOn:
        {
            [nsmstring appendString:@"PoweredOn\n"];
            
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:false], CBCentralManagerScanOptionAllowDuplicatesKey, nil];
            
            [manager scanForPeripheralsWithServices:nil options:dic];

            break;
        }
            
        default:
        {
            [nsmstring appendString:@"none\n"];
            break;
        }
    }
    
    NSLog(@"%@", nsmstring);
}

//发现设备
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    NSString *identifier = [NSString stringWithFormat:@"%@", peripheral.identifier];
    NSString * str = kStringIsEmpty(peripheral.name);
    if ([str length] > 0 && [str containsString:@"PM"]){
        self.deviceArr = @[kStringIsEmpty(peripheral.name)];
        [SVProgressHUD dismiss];
        [timer invalidate];
        
        [manager stopScan];
        peripheralFind = peripheral;
        [self.mainTable reloadData];
    }
    else if (identifier.length > 0) {
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:false], CBCentralManagerScanOptionAllowDuplicatesKey, nil];
        
        [manager scanForPeripheralsWithServices:nil options:dic];
    }
    else {
        self.deviceArr = @[];
    }
    
    NSLog(@"discover %@",peripheral.name);
}

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"connect %@",peripheral.name);
//    [self.view makeToast:@"连接成功"];
    
    // 获取数据列表
    [device peripheral:peripheralFind receiveData:2];
}

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
//    [self.view makeToast:@"连接失败"];
    NSLog(@"fail to connect %@",peripheral.name);
    NSLog(@"%@", error);
}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
 //   peripheralFind = nil;
    
//    UIAlertView * aler = [[UIAlertView alloc] initWithTitle:@"提示" message:@"断开连接" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//
//    [aler show];
    
    NSLog(@"disconnect %@, error %@",peripheral.name, error);
}

#pragma mark - FMDB
// 创建表
- (void)createTable{

   if ([self.db open]) {
       //AUTOINCREMENT 自增
       if (![self isExistTable:@"DeviceData"]) {
           BOOL result = [self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS DeviceData(ID INTEGER PRIMARY KEY AUTOINCREMENT,'uid' 'text', 'json' 'text');"];
           if (result) {
               //[ProgressHUD showSuccess:@"创建表成功"];
               [self addDeviceData];
               
           }else{
               [YJProgressHUD showMessage:@"创建表失败" inView:self.view];
           }
           [self.db close];
       }
       else {
           [self addDeviceData];
           [self.db close];
       }
   }else{
       [YJProgressHUD showMessage:@"数据库打开失败" inView:self.view];
   }
}

// 插入数据
- (void)addDeviceData {
    for (int i = 0; i < self.dataArr.count; i++) {
        //1.准备sqlite语句
        NSString *jsonStr = [self convertToJsonData:self.dataArr[i]];
        NSString *sqlite = [NSString stringWithFormat:@"insert into DeviceData(uid,json) values ('%@','%@')", defaults(@"id"), jsonStr];
        //2.执行sqlite语句
        //    char *error = NULL;//执行sqlite语句失败的时候,会把失败的原因存储到里面
        BOOL result = [self.db executeUpdate:sqlite];
        if (result) {
            NSLog(@"添加数据成功");
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateData" object:nil];
            [YJProgressHUD showMessage:NSLocalizedString(@"Read successful", nil) inView:self.view];
            if (i == self.dataArr.count - 1) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }
        } else {
            NSLog(@"添加数据失败");
            [YJProgressHUD showMessage:NSLocalizedString(@"Read failure", nil) inView:self.view];
        }
    }
}

/**
 判断一张表是否已经存在
 @param tablename 表名
 */
- (BOOL)isExistTable:(NSString *)tablename{
    NSString *sql = [NSString stringWithFormat:@"SELECT COUNT(*) FROM sqlite_master where type= 'table' and name= '%@';",tablename];
    FMResultSet *rs = [self.db executeQuery:sql];
//    BOOL result = [db executeQuery:sql];
    while ([rs next]) {
        NSInteger count = [rs intForColumnIndex:0];
        if (count == 0) {
            return NO;
        }else {
            return YES;
        }
    }
    return NO;
}

-(NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err) {
    NSLog(@"json解析失败：%@",err);
    return nil;
    }
    return dic;
}

-(NSString *)convertToJsonData:(NSDictionary *)dict {

    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }

    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];

    return mutStr;
}

#pragma mark - button Click
- (void)refreshBtnClick {
    [self connectDevice];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
